package com.aaa.marketresearch.dataresource.dao;

import com.aaa.marketresearch.dataresource.domain.Goods;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;

/**
 * @author Nail
 */

@Repository
public class GoodsDAOImpl implements GoodsDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<Goods> getAll() {
        List<Goods> result = em.createQuery("FROM Goods g").getResultList();
        return result;
    }

    @Override
    public List<Goods> getWithPartNameLike(String partName) {
        TypedQuery<Goods> query = em.createQuery("FROM Goods g WHERE lower(g.name) LIKE :partName", Goods.class);
        query.setParameter("partName", "%" + partName + "%");
        query.setMaxResults(100);
        List<Goods> result = query.getResultList();
        return result;
    }

    @Override
    public Goods getById(Integer id) {
        final String query = "FROM Goods g WHERE g.id=:id";

        Object obj = em.createQuery(query).setParameter("id", id).getSingleResult();
        if (obj != null) {
            return (Goods) obj;
        } else {
            return null;
        }
    }

    @Override
    public Goods getByBarcode(Long barcode) {
        final String query = "FROM Goods g WHERE g.barcode=:barcode";

        Object obj = em.createQuery(query).setParameter("id", barcode).getSingleResult();
        if (obj != null) {
            return (Goods) obj;
        } else {
            return null;
        }
    }

    @Override
    public void save(Goods goods) {
        this.em.merge(goods);
    }

    @Override
    public boolean delete(Integer id) {
        final String query = "DELETE Goods g WHERE g.id = :id";
        int count = em.createQuery(query).setParameter("id", id).executeUpdate();
        return (count > 0);
    }
}